<template>
  <div>
    <a-card :bordered="false" size="default" title="角色列表">
      <div class="table-operator">
        <a-button type="primary" class="btn-success" icon="plus" @click="handleAdd()">新建</a-button>
      </div>
      <a-spin :spinning="loading">
        <a-table
          ref="table"
          :columns="columns"
          :dataSource="data"
          :pagination="pagination"
          @change="handleTableChange"
          rowKey="id"
        >
          <div slot="expandedRowRender" slot-scope="record" style="margin: 0">
            <a-row :gutter="24" :style="{ marginBottom: '12px' }">
              <a-col
                :span="12"
                v-for="(role, index) in JSON.parse(record.tRoleMenuAuthority.authority)"
                :key="index"
                :style="{ marginBottom: '12px' }"
              >
                <a-col :span="4">
                  <span>{{ role.name }}：</span>
                </a-col>
                <a-col :span="20" v-if="role.permission.length > 0">
                  <a-tag color="cyan" v-for="(action, k) in role.permission" :key="k">
                    <span v-if="action === 'add'">新增</span>
                    <span v-else-if="action === 'query'">查询</span>
                    <span v-else-if="action === 'update'">修改</span>
                    <span v-else-if="action === 'get'">列表</span>
                    <span v-else-if="action === 'details'">详情</span>
                    <span v-else-if="action === 'delete'">删除</span>
                    <span v-else-if="action === 'import'">导入</span>
                    <span v-else-if="action === 'export'">导出</span>
                  </a-tag>
                </a-col>
                <a-col :span="20" v-else>-</a-col>
              </a-col>
            </a-row>
          </div>
          <span slot="authorities" slot-scope="text">
            <ellipsis :length="20" tooltip>{{ text }}</ellipsis>
          </span>
          <span slot="actions" slot-scope="text, record">
            <a-tag v-for="(action, index) in record.actionList" :key="index">{{ action }}</a-tag>
          </span>
          <span slot="operate" slot-scope="text, record">
            <template>
              <!-- <a @click="handleCheck(record)">查看</a>
              <a-divider type="vertical" /> -->
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" v-if="record.id != 40" />
              <a class="text-danger" @click="handleDelete(record)" v-if="record.id != 40">删除</a>
            </template>
          </span>
        </a-table>
      </a-spin>
      <!-- <check-modal ref="checkModal" @ok="handleOk" /> -->
      <create-form
        ref="createForm"
        :tAllMenusList="tAllMenusList"
        :tAllAuthorities="tAllAuthorities"
        :tAllInterface="tAllInterface"
        @ok="handleOk"
      />
      <edit-modal ref="editModal" :tAllMenusList="tAllMenusList" :tAllAuthorities="tAllAuthorities" @ok="handleOk" />
    </a-card>
  </div>
</template>

<script>
import moment from 'moment'
import { Ellipsis } from '@/components'
import CheckModal from './modules/role/checkModal'
import CreateForm from './modules/role/createForm'
import EditModal from './modules/role/editModal'
import { getAllPermissionList, getRolesList, deleteRoles } from '@/api/role'
import { getAllMenusList } from '@/api/menu'
import { getRoutePermission } from '@/utils/util'

export default {
  name: 'RolesList',
  components: {
    Ellipsis,
    CheckModal,
    CreateForm,
    EditModal
  },
  data () {
    return {
      // 高级搜索 展开/关闭
      advanced: false,
      routerPermission: {}, // 页面菜单权限
      radioTime: 1, // 默认选中
      data: [],
      interfaceName: [],
      interfaceNameList: [
        { name: 'IOC', checked: false },
        { name: 'IPC', checked: true },
        { name: 'IFC', checked: false }
      ],
      tAllInterface: [], // 所以接口
      tAllMenusList: [], // 所有菜单
      tAllAuthorities: [], // 所有权限
      templateDatas: [], // 接收下拉框数据的对象

      // checked1: true,
      // checked2: false,
      // checked3: false,
      tags: [],
      selectedTags: [],
      // 表头
      columns: [
        // {
        //   title: '唯一识别码',
        //   dataIndex: 'code',
        //   scopedSlots: { customRender: 'code' }
        // },
        {
          title: '角色名称',
          dataIndex: 'name',
          scopedSlots: { customRender: 'name' }
        },
        {
          title: '状态',
          dataIndex: 'status',
          width: 100,
          customRender: (text, row, index) => {
            switch (text) {
              case '1':
                return <a-badge status="success" text="正常" />
              case '0':
                return <a-badge status="error" text="禁用" />
              default:
                return text
            }
          }
        },
        {
          title: '创建时间',
          dataIndex: 'createDateLocal',
          scopedSlots: { customRender: 'createDateLocal' }
        },
        {
          title: '描述',
          dataIndex: 'description',
          scopedSlots: { customRender: 'description' }
        },
        {
          title: '操作',
          width: '150px',
          dataIndex: 'operate',
          scopedSlots: { customRender: 'operate' }
        }
      ],

      // form: this.$form.createForm(this),
      loading: true,
      visible: false,
      confirmLoading: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      form: null,
      mdl: {},
      // 分页属性
      pagination: {
        defaultPageSize: 10,
        pageNo: 0,
        pageSize: 10, // 默认每页显示数量
        showSizeChanger: true, // 显示可改变每页数量
        showQuickJumper: true, // 是否可以快速跳转至某页
        pageSizeOptions: ['10', '20', '50', '100'], // 每页数量选项
        showTotal: (total) => this.$t('pagination.total') + ` ${total} ` + this.$t('pagination.items'), // 分页中显示总的数据
        total: 0 // 总条数
      },
      // 查询参数
      queryParam: {}
    }
  },
  created () {},
  mounted () {
    this.getRolesList()
    // this.getPermission()
  },

  methods: {
    // 获取当前页面的权限
    getPermission () {
      this.routerPermission = getRoutePermission(this.$route.name)
      console.log('当前页面操作权限-------', this.routerPermission)
    },
    // 转换成树形菜单
    toTree (data) {
      const result = []
      if (!Array.isArray(data)) {
        return result
      }
      data.forEach((item) => {
        delete item.children
      })
      const map = {}
      data.forEach((item) => {
        map[item.id] = item
      })
      data.forEach((item) => {
        const parent = map[item.pid]
        if (parent) {
          ;(parent.children || (parent.children = [])).push(item)
        } else {
          result.push(item)
        }
      })
      return result
    },
    // 菜单排序方法
    sortBykey (ary, key) {
      return ary.sort(function (a, b) {
        const x = a[key]
        const y = b[key]
        return x < y ? -1 : x > y ? 1 : 0
      })
    },
    // 获取菜单列表
    getAllMenusList () {
      getAllMenusList()
        .then((response) => {
          console.log('菜单列表+++++----', response)
          response.forEach((item) => {
            item.title = item.name
            item.key = item.id
          })
          this.sortBykey(response, 'sort')
          this.tAllMenusList = this.toTree(response)
          console.log('start', this.treeData)
        })
        .catch((error) => {
          console.log(error)
        })
    },
    // 获取权限列表
    getAllPermissionList () {
      getAllPermissionList()
        .then((response) => {
          response.forEach((item) => {
            item.actions = JSON.parse(item.actions)
            item.selected = []
            item.actionsFormat = this.actionsFormat(item.actions)
          })
          this.sortBykey(response, 'id')
          this.tAllAuthorities = response
          // console.log('xsasasadasd=====', this.tAllAuthorities)
          // console.log('权限列表----', this.permissions)
        })
        .catch((error) => {
          console.log(error)
        })
    },

    // 查看
    handleCheck (record) {
      this.$refs.checkModal.check(record)
    },
    // 新增
    handleAdd () {
      this.showCreateModal = true
      this.$refs.createForm.add()
      this.getAllMenusList()
      this.getAllPermissionList()
    },

    // 编辑
    handleEdit (record) {
      console.log('编辑record-------', record)
      this.$refs.editModal.edit(record) // $refs指弹出框的所有方法，edit只是modal框的一个方法
      this.getAllMenusList()
      this.getAllPermissionList()
    },

    // 删除
    handleDelete (record) {
      this.$confirm({
        title: '提示',
        content: `你确定要删除 ${record.name} 角色  吗?`,
        okText: '确定',
        okType: 'primary',
        cancelText: '取消',
        onOk: () => {
          deleteRoles({ rolesId: record.id }).then((res) => {
            // 存储成功、刷新列表
            this.$notification['success']({
              message: '提示',
              description: '数据删除成功'
            })
            if (this.data.length === 1) {
              this.pagination.pageNo = this.pagination.pageNo - 1
            }
            this.getRolesList()
          })
        },
        onCancel () {
          console.log('Cancel')
        }
      })
    },

    handleChange (tag, checked) {
      const { selectedTags } = this
      const nextSelectedTags = checked ? [...selectedTags, tag] : selectedTags.filter((t) => t !== tag)
      console.log('You are interested in: ', nextSelectedTags)
      this.selectedTags = nextSelectedTags
    },

    handleCancel () {
      this.visible = false
    },

    // 获取列表
    getRolesList () {
      const filter = { sort: 'id,desc', page: this.pagination.pageNo, size: this.pagination.pageSize }
      this.loading = true
      getRolesList(filter)
        .then((response) => {
          console.log('角色列表----', response)
          response.data.forEach((item) => {
            // console.log('打印每个角色----', item)
            item.fullName = item.firstName + item.lastName
            item.createDate = moment(item.createDate).format('YYYY-MM-DD HH:mm:ss')
            item.modifyDate = moment(item.modifyDate).format('YYYY-MM-DD HH:mm:ss')
          })
          this.loading = false
          this.data = response.data
          this.pagination.total = Number(response.totalCount)
        })
        .catch((error) => {
          console.log(error)
        })
    },

    // 更新列表
    handleOk () {
      // this.$refs.table.refresh()
      this.getRolesList()
    },
    // 分页方法
    handleTableChange (pagination) {
      console.log('分页事件-----------', pagination)
      this.pagination.current = pagination.current
      this.pagination.pageNo = pagination.current - 1
      this.pagination.pageSize = pagination.pageSize
      // if (this.selectedTags.length === 0) {
      //   this.getDictionariesList()
      // } else {
      //   this.refresh()
      // }
      this.getRolesList()
    },

    interfaceNameChange (item) {
      console.log(this.interfaceNameList)
      console.log(this.interfaceName)
    },

    actionsFormat (resource) {
      var res = []
      for (const i in resource) {
        let label = ''
        if (resource[i] === 'add') {
          label = '新增'
        } else if (resource[i] === 'query') {
          label = '查询'
        } else if (resource[i] === 'get') {
          label = '列表'
        } else if (resource[i] === 'update') {
          label = '修改'
        } else if (resource[i] === 'details') {
          label = '详情'
        } else if (resource[i] === 'delete') {
          label = '删除'
        }
        res.push({
          label: label,
          value: resource[i]
        })
      }

      return res
    }
  }
}
</script>

<style>
.ant-card-body {
  padding: 20px !important;
}
.antd-pro-components-standard-form-row-index-label > span {
  width: 150px;
  height: auto !important;
  border-right: 3px solid #1890ff;
  background: #e6f7ff;
}
.table-page-search-wrapper .ant-form-inline .ant-form-item .ant-form-item-control-wrapper {
  margin-top: 5px !important;
}
.table-page-search-wrapper .ant-form-inline .ant-form-item .ant-form-item-label {
  margin-top: 5px !important;
}
</style>
<style lang="less" scoped>
.table-operator {
  margin-bottom: 10px;
}
/deep/ .ant-card-head {
  padding: 0 20px;
}
.table-page-search-wrapper .ant-form-inline .ant-form-item {
  margin-bottom: 0;
}
.ant-pro-components-tag-select {
  /deep/ .ant-pro-tag-select .ant-tag {
    margin-right: 24px;
    padding: 0 8px;
    font-size: 14px;
  }
}
.ant-pro-pages-list-projects-cardList {
  margin-top: 24px;

  /deep/ .ant-card-meta-title {
    margin-bottom: 4px;
  }

  /deep/ .ant-card-meta-description {
    height: 44px;
    overflow: hidden;
    line-height: 22px;
  }

  .cardItemContent {
    display: flex;
    height: 20px;
    margin-top: 16px;
    margin-bottom: -4px;
    line-height: 20px;

    > span {
      flex: 1 1;
      color: rgba(0, 0, 0, 0.45);
      font-size: 12px;
    }

    /deep/ .ant-pro-avatar-list {
      flex: 0 1 auto;
    }
  }
}
</style>
<style lang="less" scoped>
.checkable {
  margin-bottom: 10px;
  padding: 5px 0;
  border-bottom: 1px dashed #e8e8e8;
  > span {
    float: left;
    padding-right: 5px;
    width: 100px;
    color: #888;
    height: auto !important;
  }
  .checkable-right {
    margin-left: 100px;
    .ant-tag-checkable {
      color: #333;
    }
    .ant-tag-checkable-checked {
      color: #fff;
    }
  }
}
.search-btn-handle {
  .table-page-search-submitButtons {
    float: right;
  }
}
.ant-table-default {
  background: #f00 !important;
  .ant-table-content {
    .ant-table-thead > tr > th > {
      padding: 10px 16px;
    }
    .ant-table-tbody > tr > td > {
      padding: 10px 16px;
    }
  }
}
.antd-pro-components-standard-form-row-index-standardFormRow {
  margin-bottom: 6px !important;
  padding-bottom: 6px !important;
}
.antd-pro-components-standard-form-row-index-standardFormRow .antd-pro-components-standard-form-row-index-label {
  line-height: 39.9999px;
}
</style>
